//
//  KAPwdSetVC.swift
//  kano
//
//  Created by Sophia on 2024/8/20.
//

import UIKit
import RxCocoa
import RxSwift

class KAPwdSetVC: KABaseVC {
    //短信验证码返回codeToken
    var msgCodeToken: String = ""
    //短信验证码code更贴切
    var msgCode: String = ""
    
    private let disposeBag = DisposeBag()

    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = UIColor.white
        var_cornerView.layer.cornerRadius = kscale(30)
        var_cornerView.layer.masksToBounds = true
        var_cornerView.frame = CGRectMake(kscale(20), UIDevice.ka_fullNavHeight+kscale(40), var_screenWidth-kscale(40), kscale(330))
        return var_cornerView
    }()
    
    lazy var var_titleLabel: UILabel = {
        let var_titleLabel = UILabel()
        var_titleLabel.x = kscale(20)
        var_titleLabel.y = kscale(32)
        var_titleLabel.width = var_cornerView.width-kscale(40)
        var_titleLabel.height = kscale(32)
        var_titleLabel.textAlignment = .center
        var_titleLabel.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        var_titleLabel.textColor = .black
        var_titleLabel.text = "Password setting"
        return var_titleLabel
    }()
    
    lazy var var_pwdView: KAPwdView = {
        var_pwdView = KAPwdView(placeHolder: "Please enter six letters or numbers")
        var_pwdView.x = kscale(20)
        var_pwdView.y = kscale(95)
        var_pwdView.size = CGSizeMake(var_cornerView.width-kscale(40), kscale(48))
        return var_pwdView
    }()
    
    lazy var var_confirmPwdView: KAPwdView = {
        var_confirmPwdView = KAPwdView(placeHolder: "Confirm password")
        var_confirmPwdView.x = kscale(20)
        var_confirmPwdView.y = var_pwdView.bottom+kscale(16)
        var_confirmPwdView.size = CGSizeMake(var_cornerView.width-kscale(40), kscale(48))
        return var_confirmPwdView
    }()
    
    lazy var var_signBtn: UIButton = {
        let var_signBtn = UIButton(frame: CGRectMake(kscale(48), var_confirmPwdView.bottom+kscale(32), var_cornerView.width-kscale(96), kscale(50.0)))
        var_signBtn.setTitle("SignUp", for: .normal)
        var_signBtn.setTitleColor(.white, for: .normal)
        var_signBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_signBtn.backgroundColor = .colorBDBDF5
        var_signBtn.layer.cornerRadius = kscale(25)
        var_signBtn.layer.masksToBounds = true
        var_signBtn.addTarget(self, action: #selector(ka_signButtonClick), for: .touchUpInside)
        return var_signBtn
    }()
}

extension KAPwdSetVC {
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_setUI()
        ka_bindUI()
    }
    
    func ka_setUI() {
        view.backgroundColor = .colorf2f2f5
        ka_showCustomerNavBar(type: .normal)
        var_navBar.updateUI(alpha: 0)
        
        view.addSubview(var_cornerView)
        var_cornerView.addSubview(var_titleLabel)
        var_cornerView.addSubview(var_pwdView)
        var_cornerView.addSubview(var_confirmPwdView)
        var_cornerView.addSubview(var_signBtn)
    }
    
    func ka_bindUI() {
        var_pwdView.contentTF.rx.text
            .orEmpty
            .map { text in
                return (text.count == 4 || text.count == 6) ? .themeColor : .colorBDBDF5
            }
            .bind(to: var_signBtn.rx.backgroundColor)
            .disposed(by: disposeBag)
        
//        var_checkBox.rx.tap
//            .subscribe(onNext: { [weak self] in
//                self!.var_checkBox.isSelected = !self!.var_checkBox.isSelected
//            })
//            .disposed(by: disposeBag)
    }
    
    @objc func ka_signButtonClick() {
        guard var_pwdView.contentTF.text!.verifyPwd else {
            view.makeToast("Please enter 6 digits or letters"); return
        }
        guard var_confirmPwdView.contentTF.text!.verifyPwd else {
            view.makeToast("Please enter 6 digits or letters"); return
        }
        if var_confirmPwdView.contentTF.text != var_pwdView.contentTF.text {
            view.makeToast("The two passwords are inconsistent")
            return
        }
        ka_registerPwd()
    }
    
    @objc func ka_registerPwd() {
        let mobile = KAUserManager.shared.user.mobile
        let installDate = UserDefaults.standard.value(forKey: "InstallTime") as? Date
//        view.showLoading()
        let paramDic: [String: Any] = [

            "password": var_pwdView.contentTF.text!,
            "mobile": mobile,
            "backMobile": mobile,
            "grantType": KAOperation.Register.rawValue,
            "codeToken": msgCodeToken,
            "pictureVerifyCode": msgCode,
            "verifyCode": msgCode,
            "installTime": installDate?.timeIntervalSince1970 ?? 0,
            "appsflyerId": KAAFTool.shared.appFlyerId(),
            "needSaveVerifyFlag": 1,
            "zuid": UIDevice.ka_UUID,
            
            "cliendId": UIDevice.ka_UUID,
            "clientType": "1",
            "userAgent": "",
            "userGoogleGid": "",
            "gmail": "",
            "invitationCode": "",
            "channelUserGid": "",
            "unionId": "",
            "voucherGid": "",
            "voucherShowType": "",
            "extendInfo": "",
            "accessToken": "",
        ]
        view.showLoading()
        loginProvider.request(.registerPwd(paramDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAUser>.handleResponseData(response.data) { isSuccess, message, response in
                        
                        if isSuccess {
                            guard let user = response?.content else { return }
                            let defaultUser = KAUserManager.shared.user
                            var newUser = defaultUser.merge(with: user)
                            newUser.isLogin = true
                            KAUserManager.shared.user = newUser
                            KAUserManager.shared.userLogin(with: newUser.mobile)
                            
                            KAReport.ka_reportWith(type: .device)
                            KAReport.ka_reportWith(type: .loaction)
                            //注册成功
                            KAAFTool.logEvent(event: "SKP_registered_successfully")
                            //注册成功跳转首页
                            KAAFTool.logEvent(event: "SKP_redirect_homepage")
                            
                            if KALocationManager.shared.status == .authorizedAlways || KALocationManager.shared.status == .authorizedWhenInUse {
                                KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : true])
                            } else {
                                KAReport.ka_reportWith(type: .permissionLoc, data: ["permit" : false])
                            }
                            
                        } else {
                            self.view.makeToast(message)
                            //注册失败
                            KAAFTool.logEvent(event: "SKP_registered_failed")

                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                    //注册失败
                    KAAFTool.logEvent(event: "SKP_registered_failed")

                }
            case .failure(let error):
                print(error.localizedDescription)
                //注册失败
                KAAFTool.logEvent(event: "SKP_registered_failed")
            }
        }
    }
    
    
}
